import React, { useState, useEffect, useRef, useCallback } from "react";
import "./Barrage.css";
import { Input, Button, Select, Dropdown,  } from "antd"; // 移除Upload组件
import { SmileOutlined } from "@ant-design/icons";

// 修改：emoji类型定义（移除url，添加emoji字段）
interface Emoji {
  key: string;
  name: string;
  emoji: string;
}

// 修改：emoji数据（使用实际emoji字符）
const emojis: Emoji[] = [
  { key: "1", name: "微笑", emoji: "😊" },
  { key: "2", name: "大笑", emoji: "😂" },
  { key: "3", name: "喜欢", emoji: "👍" },
  { key: "4", name: "生气", emoji: "😠" },
  { key: "5", name: "哭泣", emoji: "😭" },
  { key: "6", name: "惊讶", emoji: "😲" },
  { key: "7", name: "爱心", emoji: "❤️" },
  { key: "8", name: "加油", emoji: "💪" },
];

// 新增：敏感词列表（可根据需求扩展）
const sensitiveWords = [
  "傻逼",
  "你妈",
  "fuck",
  "sb",
  "草",
  "操",
  "死",
  "滚",
  "垃圾",
  "傻子",
  "尼玛",
  "操尼玛",
  "草你妈",
];

// 新增：敏感词过滤函数
const filterSensitiveWords = (text: string): string => {
  if (!text) return text;
  // 创建敏感词正则表达式，全局匹配不区分大小写
  const regex = new RegExp(sensitiveWords.join("|"), "gi");
  // 将匹配到的敏感词替换为***
  return text.replace(regex, "***");
};

// 弹幕消息类型定义
interface BarrageMessage {
  id: string;
  content: string;
  type: "text"; // 移除image类型
  color: string;
  fontSize: number;
  speed: number;
  position: number;
}

interface BarrageProps {
  // 视频元素的引用
  videoRef: React.RefObject<HTMLVideoElement>;

  // 是否显示输入区域
  flag?: boolean;
}
const Barrage: React.FC<BarrageProps> = ({ videoRef, flag }) => {
  // 弹幕消息
  const [messages, setMessages] = useState<BarrageMessage[]>([]);
  // 输入框内容
  const [inputContent, setInputContent] = useState("");
  // 删除：selectedImage状态
  // 弹幕速度
  const containerRef = useRef<HTMLDivElement>(null);
  // 视频是否暂停
  const [isPaused, setIsPaused] = useState(false);
  // 弹幕速度
  const [barrageSpeed, setBarrageSpeed] = useState<number>(5);
  // 字体大小
  const [fontSize, setFontSize] = useState<number>(24);
  // 添加颜色状态
  const [fontColor, setFontColor] = useState<string>("#FFFFFF");
  // 添加最大弹幕数量限制
  const MAX_MESSAGES = 20;
  useEffect(() => {
    // 使用传入的videoRef.current获取视频元素
    const videoElement = videoRef.current;
    // 检查videoElement是否存在
    if (!videoElement) return;
    // 监听视频暂停和播放
    const handlePause = () => setIsPaused(true);
    const handlePlay = () => setIsPaused(false);
    // 绑定事件监听
    videoElement.addEventListener("pause", handlePause);
    videoElement.addEventListener("play", handlePlay);

    return () => {
      // 移除事件监听
      videoElement.removeEventListener("pause", handlePause);
      videoElement.removeEventListener("play", handlePlay);
    };
  }, [videoRef]);

  // 发送弹幕
  const sendBarrage = useCallback(
    (type: "text", content: string = "") => {
      // 移除image类型
      if ((!inputContent && !content) || !videoRef.current) return;

      // 对文本内容进行敏感词过滤
      const filteredContent = filterSensitiveWords(content || inputContent);

      const newMessage: BarrageMessage = {
        id: Date.now().toString(),
        content: filteredContent,
        type: "text", // 固定为text类型
        color: fontColor,
        fontSize: fontSize,
        speed: barrageSpeed,
        position: Math.floor(Math.random() * 6) * 10,
      };

      // 限制最大弹幕数量
      setMessages((prev) => {
        const newMessages = [...prev, newMessage];
        return newMessages.length > MAX_MESSAGES
          ? newMessages.slice(-MAX_MESSAGES)
          : newMessages;
      });

      // 清空输入框
      setInputContent("");
      // 删除：清空图片选择器的代码
    },
    [inputContent, videoRef, fontSize, barrageSpeed, fontColor] // 移除selectedImage依赖
  );
  // 渲染弹幕消息
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    // 为每个新消息创建动画
    const messageElements = container.querySelectorAll(
      ".barrage-message:not([data-animated])"
    );
    messageElements.forEach((el) => {
      (el as HTMLElement).setAttribute("data-animated", "true");
    });
  }, [messages]);

  // 新增：添加表情到输入框的函数
  const addEmojiToInput = (emoji: string) => {
    setInputContent((prevContent) => prevContent + emoji);
  };

  // 新增：创建表情包菜单
  const emojiMenuItems = emojis.map((emoji) => ({
    key: emoji.key,
    label: (
      <div style={{ textAlign: "center", padding: "5px" }}>
        <div style={{ fontSize: "24px" }}>{emoji.emoji}</div>
        <div style={{ fontSize: "12px" }}>{emoji.name}</div>
      </div>
    ),
    onClick: () => addEmojiToInput(emoji.emoji), // 修改：调用addEmojiToInput而不是sendBarrage
  }));

  // 删除：原sendEmoji函数

  return (
    <div
      ref={containerRef}
      className="barrage-container"
      style={{
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        pointerEvents: "none",
        display: flag ? "block" : "none",
      }}
    >
      {/* 弹幕消息容器 */}
      <div className="barrage-messages">
        {messages.map((msg) => (
          <div
            key={msg.id}
            className="barrage-message"
            style={{
              position: "absolute",
              top: `${msg.position}%`,
              left: "90%",
              color: msg.color,
              fontSize: `${msg.fontSize}px`,
              whiteSpace: "nowrap",
              textShadow: "0 0 2px rgba(0,0,0,0.7), 0 0 4px rgba(0,0,0,0.5)",
              animation: `barrage-slide ${msg.speed}s ease-in forwards`,
              pointerEvents: "auto",
              animationPlayState: isPaused ? "paused" : "running",
              transition: "all 0.2s",
              cursor: "pointer",
            }}
            onClick={() =>
              setMessages((prev) => prev.filter((m) => m.id !== msg.id))
            }
          >
            {msg.content} {/* 移除图片显示逻辑 */}
          </div>
        ))}
      </div>

      {/* 弹幕输入区域 */}
      {flag && (
        <div
          className="barrage-input-area"
          style={{
            height: "50px",
            zIndex: "100",
            position: "absolute",
            bottom: 0,
            left: "50%",
            transform: "translateX(-50%)",
            display: "flex",
            gap: 12,
            alignItems: "center",
            pointerEvents: "auto",
            margin: "auto",
            padding: "8px 16px",
            backgroundColor: "rgba(0,0,0,0.5)",
            borderRadius: 4,
          }}
        >
          {/* 移除每个控制项的外层div，直接使用flex布局排列 */}
          <h4 style={{ marginRight: 8, color: "white", marginBottom: 0 }}>
            速度
          </h4>
          <Select
            value={barrageSpeed}
            onChange={(value) => setBarrageSpeed(value)}
            style={{ width: 90 }}
            options={[
              { label: "极慢", value: 10 },
              { label: "慢速", value: 8 },
              { label: "中速", value: 5 },
              { label: "快速", value: 3 },
              { label: "极快", value: 2 },
            ]}
          />

          <h4 style={{ marginRight: 8, color: "white", marginBottom: 0 }}>
            大小
          </h4>
          <Select
            value={fontSize}
            onChange={(value) => setFontSize(value)}
            style={{ width: 90 }}
            options={[
              { label: "小", value: 16 },
              { label: "中", value: 24 },
              { label: "大", value: 32 },
              { label: "特大", value: 40 },
            ]}
          />

          <h4 style={{ marginRight: 8, color: "white", marginBottom: 0 }}>
            颜色
          </h4>
          <Select
            value={fontColor}
            onChange={(value) => setFontColor(value)}
            style={{ width: 90 }}
            options={[
              { label: "白色", value: "#FFFFFF" },
              { label: "红色", value: "#FF0000" },
              { label: "黄色", value: "#FFFF00" },
              { label: "绿色", value: "#00FF00" },
              { label: "蓝色", value: "#0000FF" },
            ]}
          />

          <Input
            value={inputContent}
            onChange={(e) => setInputContent(e.target.value)}
            placeholder="输入弹幕文字..."
            onPressEnter={() => sendBarrage("text")}
            style={{ width: 300 }}
          />
          <Dropdown
            menu={{
              items: emojiMenuItems,
              style: {
                width: "300px",
                // padding: "10px",
                backgroundColor: "white",
                display: "grid",
                gridTemplateColumns: "repeat(4, 1fr)",
                gap: "8px",
                overflow: "hidden", // 添加此行来隐藏滚动条
              },
            }}
            trigger={["click"]}
            placement="top" // 设置下拉菜单显示在按钮上方
          >
            <Button
              icon={<SmileOutlined />}
              size="small"
              style={{
                backgroundColor: "rgba(255,255,255,0.2)",
                border: "none",
              }}
            ></Button>
          </Dropdown>

          <Button onClick={() => sendBarrage("text")}>发送</Button>
        </div>
      )}
    </div>
  );
};

export default Barrage;
